import React, { Component } from 'react'
import { Button, Form, Input, Space, Steps } from 'antd'
import _ from 'lodash'
import CountTimeDown from './CountTimeDown'
import TheDialog from '@/components/TheDialog'
import TheButton from '../../../components/TheButton'
import Negotiate from './components/negotiate'
import { CloseCircleFilled } from '@ant-design/icons'
import '../style/style.less'
import { getDateTime2 } from '@/utils/getDate'

const { Step } = Steps

export default class ChargebackSteps extends Component {
  roleIds = sessionStorage.getItem('roleName')
  negotiateRef = React.createRef()
  state = {
    stepData: [],
    current: 0,
    moneyStatus: 'N',
    salesStatus: 1,
    date: null,
  }
  async componentDidMount() {
    await this.Minutes()
    this.getStepData()
  }
  /**
   * 倒计时实现
   * @constructor
   */
  Minutes = () => {
    let date = new Date(this.props.countdown)
    let min = date.getMinutes()
    date.setMinutes(min)
    let newdate = date.toLocaleString('chinese', { hour12: false })
    this.setState({
      date: newdate,
    })
  }
  getStepData = () => {
    const { moneyStatus, salesStatus, autoAgreeRefund, autoAgreeRefundSetting } = this.props
    console.log(autoAgreeRefund, 'autoAgreeRefund');
    let stepData = []
    let current = 0
    switch (parseInt(salesStatus)) {
      case 1:
        switch (moneyStatus) {
          case 'Y':
            stepData = [
              {
                title: '买家发起退款申请',
                description: '',
              },
              {
                title: (
                  <div className="steps-timer">
                    <span>商家处理</span>
                    {
                      autoAgreeRefund === 0  ? (<span>剩余
                        < CountTimeDown endTime={this.state.date} /></span>) : null
                    }

                  </div>
                ),
                description: (

                  <Space>
                    <TheButton type='primary' size="middle" hasPermi={['order:mallChargeback:refund']} onClick={this.refundConfirmGood}>
                      同意
                    </TheButton>
                    <TheButton type='default' size="middle" hasPermi={['order:mallChargeback:refund']} onClick={this.refundRefuse}>
                      拒绝
                    </TheButton>
                    <TheButton hasPermi={['order:mallChargeback:negotiateHistory']} type='default' size="middle" onClick={this.negoHistory}>
                      协商历史
                    </TheButton>
                    {
                      autoAgreeRefund === 0 ? <TheButton style={{ zIndex: 2 }} hasPermi={['order:mallChargeback:hangUp']} type='danger' size="middle" onClick={this.refundHangUp}>
                        纠纷处理开启
                      </TheButton> : <TheButton type='danger' size="middle" >
                        纠纷处理中...
                      </TheButton>
                    }
                  </Space>
                ),
              },
              {
                title: '买家寄回商品',
                description: '',
              },
              {
                title: '商家确认收货',
                description: '',
              },
              {
                title: '完成',
                description: '',
              },
            ]
            current = 1
            break
          case 'N':
            stepData = [
              {
                title: '买家发起退款申请',
                description: '',
              },
              {
                title: (
                  <div className="steps-timer">
                    <span>商家处理</span>
                    {
                      autoAgreeRefund === 0 ? (<span>剩余
                      <CountTimeDown endTime={this.state.date}/></span>) : null
                    }
                  </div>
                ),
                description: (
                  <Space>
                    <TheButton hasPermi={['order:mallChargeback:refund']} type='primary' size="middle" onClick={this.refundConfirm}>
                      同意
                    </TheButton>
                    <TheButton hasPermi={['order:mallChargeback:refund']} type='default' size="middle" onClick={this.refundRefuse}>
                      拒绝
                    </TheButton>
                    <TheButton hasPermi={['order:mallChargeback:negotiateHistory']} type='default' size="middle" onClick={this.negoHistory}>
                      协商历史
                    </TheButton>
                    {autoAgreeRefund === 0 ? <TheButton hasPermi={['order:mallChargeback:hangUp']} type='danger' size="middle" onClick={this.refundHangUp}>
                      纠纷处理开启
                    </TheButton> : <TheButton type='danger' size="middle"  >
                      纠纷处理中...
                    </TheButton>}
                  </Space>
                ),
              },
              {
                title: '完成',
                description: '',
              },
            ]
            current = 1
            break
        }
        break
      case 2:
        switch (moneyStatus) {
          case 'Y':
            stepData = [
              {
                title: '买家发起退款申请',
                description: '',
              },
              {
                title: `商家同意退款`,
                description: '',
              },
              {
                title: '买家寄回商品',
                description: '',
              },
              {
                title: '商家确认收货',
                description: '',
              },
              {
                title: '完成',
                description: '',
              },
            ]
            current = 1
            break
        }
        break
      case 3:
        stepData = [
          {
            title: '买家发起退款申请',
            description: '',
          },
          {
            title: `商家同意退款`,
            description: '',
          },
          {
            title: '买家寄回商品',
            description: '',
          },
          {
            title: '商家确认收货',
            description: (
              <Space>
                <TheButton type='primary' size="middle" hasPermi={['order:mallChargeback:viewLogistics']} onClick={this.onLogistics}>
                  查看物流
                </TheButton>

                <TheButton type='primary' size="middle" hasPermi={['order:mallChargeback:refuse']} onClick={this.confirmGood}>
                  收货
                </TheButton>
                <TheButton type='default' size="middle" hasPermi={['order:mallChargeback:refuse']} onClick={this.openGoodDialog}>
                  拒绝
                </TheButton>
              </Space>
            ),
          },
          {
            title: '完成',
            description: '',
          },
        ]
        current = 3
        break
      case 9:
        switch (moneyStatus) {
          case 'N':
            stepData = [
              {
                title: '买家发起退款申请',
                description: '',
              },
              {
                title: `商家同意退款`,
                description: '',
              },
              {
                title: '退款成功',
                description: '',
              },
            ]
            current = 2
            break
          case 'Y':
            stepData = [
              {
                title: '买家发起退款申请',
                description: '',
              },
              {
                title: `商家同意退款`,
                description: '',
              },
              {
                title: '买家寄回商品',
                description: '',
              },
              {
                title: '商家确认收货',
                description: '',
              },
              {
                title: '退款成功',
                description: '',
              },
            ]
            current = 4
            break
        }
        break
      case 4:
        stepData = [
          {
            title: '买家发起退款申请',
            description: '',
          },
          {
            title: `商家拒绝退款`,
            description: '',
          },
          {
            title: '退款失败',
            description: '',
          },
        ]
        current = 2
        break
      case 5:
        stepData = [
          {
            title: '买家发起退款申请',
            description: '',
          },
          {
            title: `商家同意退款`,
            description: '',
          },
          {
            title: '买家超时未寄回商品',
            description: '',
          },
          {
            title: '退款失败',
            description: '',
          },
        ]
        current = 3
        break
      case 6:
        stepData = [
          {
            title: '买家发起退款申请',
            description: '',
          },
          {
            title: `商家同意退款`,
            description: '',
          },
          {
            title: '买家已寄回商品',
            description: '',
          },
          {
            title: '商家拒绝收货',
            description: '',
          },
          {
            title: '退款失败',
            description: '',
          },
        ]
        current = 4
        break
    }
    this.setState({
      stepData,
      current,
    })
  }
  refundHangIng = () => {
    React.$confirm({
      title: '纠纷处理开启后将暂停超时退款，纠纷处理完成后需手动处理订单',
      onOk: () => {

      },
    })
  }
  refundHangUp = () => {
    const { salesId } = this.props
    React.$confirm({
      title: '纠纷处理开启后将暂停超时退款，纠纷处理完成后需手动处理订单，您确认开启吗？',
      onOk: () => {
        React.$postJson('/management/shopSalesReturn/updateAutoAgreeRefundState/Json', {
          autoAgreeRefund: 1,//0-开启, 1-挂起
          shopSalesReturnId: salesId//退款订单id
        }).then(
          (res) => {
            if (res.code === 0) {
              React.$message({
                type: 'info',
                content: '操作成功',
              })

              window.location.reload()
            }
          }
        )
      },
    })
  }

  negoHistory = () => {
    this.negotiateRef.current.open()
  }
  refundConfirmGood = () => {
    React.$confirm({
      title: '您确认同意退款退货吗？',
      onOk: () => {
        const { salesId } = this.props
        React.$post('/management/shopSalesReturn/refundConfirmGood', { salesId }).then(
          (res) => {
            if (res.code === 0) {
              React.$message({
                type: 'info',
                content: '退款退货成功',
              })
              window.location.reload()
            }
          }
        )
      }
    })
  }
  refundConfirm = () => {
    const { salesId } = this.props
    React.$confirm({
      title: '您确认退款吗？',
      onOk: () => {
        React.$post('/management/shopSalesReturn/refundConfirm', { salesId }).then(
          (res) => {
            if (res.code === 0) {
              React.$message({
                type: 'info',
                content: '退款成功',
              })
              window.location.reload()
            }
          }
        )
      }
    })
  }
  refundRefuse = () => {
    React.$confirm({
      title: '您确认拒绝退款吗？',
      onOk: () => {
        this.setState({
          visible: true,
        })
      },
    })
  }
  handleCancel = () => {
    this.setState({
      visible: false,
    })
  }
  saveRefundRefuse = (value) => {
    const { salesId } = this.props
    React.$post('/management/shopSalesReturn/refundRefuse', {
      salesId,
      ...value,
    }).then((res) => {
      if (res.code === 0) {
        React.$message({
          type: 'info',
          content: '拒绝退款成功',
        })
        // window.location.reload()
        window.history.back()
      }
    })
  }
  confirmGood = () => {
    React.$confirm({
      title: '您确认收货吗？',
      onOk: () => {
        const { salesId } = this.props
        React.$post('/management/shopSalesReturn/storeConfirmGood', { salesId }).then(
          (res) => {
            if (res.code === 0) {
              React.$message({
                type: 'info',
                content: '确认收货成功',
              })
              window.location.reload()
            }
          }
        )
      },
    })
  }
  openGoodDialog = () => {
    this.setState({ goodVisible: true })
  }
  saveRefuseGood = (value) => {
    const { salesId } = this.props
    React.$post('/management/shopSalesReturn/storeRefuseGood', { salesId, ...value }).then(
      (res) => {
        if (res.code === 0) {
          React.$message({
            type: 'info',
            content: '拒绝收货成功',
          })
          this.setState({ goodVisible: false })
          // window.location.reload()
          window.history.back()
        }
      }
    )
  }
  logDialogCancel = () => {
    this.setState({
      logisticsInformation: null,
      logVisible: false,
    })
  }
  onLogistics = async () => {
    const {
      dataSource: { shopSalesReturnId },
    } = this.props
    React.$post(`/management/shopOrderInfo/checkLogisticsRefund/${shopSalesReturnId}`).then((response) => {
      if (response.code === 0 && response.data) {
        let {
          msg: { context },
        } = response.data
        context = context
          ? context.map((v) => {
            let time = v.time * 1000
            time = new Date(parseInt(time))
            time = getDateTime2(time)
            return {
              ...v,
              time,
            }
          })
          : null
        this.setState({
          logisticsInformation: context,
          logVisible: true,
        })
      } else {
        return React.$message({
          type: 'info',
          content: '暂无物流信息',
        })
      }
    })
  }
  render() {
    const { visible, goodVisible, logVisible, logisticsInformation } = this.state
    const {
      dataSource: { refuseComment },
      salesStatus,
    } = this.props
    return (
      <div>
        {parseInt(salesStatus) !== 0 && (
          <Steps progressDot current={this.state.current}>
            {_.map(this.state.stepData, (v) => {
              return (
                <Step
                  title={v.title}
                  description={
                    <div className={'order-details-time'}>{v.description}</div>
                  }
                />
              )
            })}
          </Steps>
        )}
        {parseInt(salesStatus) === 7 && (
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
            }}>
            <CloseCircleFilled
              style={{ color: '#2b6dea', fontSize: 50, marginRight: 20 }}
            />
            <div>
              <div style={{ fontSize: 14, color: '#2b6dea' }}>退款取消</div>
            </div>
          </div>
        )}
        {parseInt(salesStatus) === 0 && (
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
            }}>
            <CloseCircleFilled
              style={{ color: '#2b6dea', fontSize: 50, marginRight: 20 }}
            />
            <div>
              <div style={{ fontSize: 14, color: '#2b6dea' }}>退款关闭</div>
              <div style={{ fontSize: 14, color: '#2b6dea', marginTop: 5 }}>
                <span style={{ marginRight: 10 }}>原因:</span>
                <span>{refuseComment}</span>
              </div>
            </div>
          </div>
        )}
        <TheDialog
          visible={visible}
          title={'拒绝退款'}
          handleCancel={this.handleCancel}
          footer={null}
          width={400}>
          <Form onFinish={this.saveRefundRefuse}>
            <Form.Item
              name="refuseReason"
              label="备注"
              rules={[{ required: true }]}>
              <Input.TextArea maxLength={20} showCount allowClear />
            </Form.Item>
            <Form.Item>
              <div
                style={{
                  display: 'flex',
                  justifyContent: 'flex-end',
                  marginBottom: -30,
                }}>
                <Space>
                  <Button onClick={this.handleCancel}>取消</Button>
                  <Button type="primary" htmlType="submit">
                    确认
                  </Button>
                </Space>
              </div>
            </Form.Item>
          </Form>
        </TheDialog>
        <TheDialog
          visible={goodVisible}
          title={'拒绝收货'}
          handleCancel={() => this.setState({ goodVisible: false })}
          footer={null}
          width={400}>
          <Form onFinish={this.saveRefuseGood}>
            <Form.Item
              name="refuseReason"
              label="备注"
              rules={[{ required: true }]}>
              <Input.TextArea maxLength={20} allowClear showCount />
            </Form.Item>
            <Form.Item>
              <div
                style={{
                  display: 'flex',
                  justifyContent: 'flex-end',
                  marginBottom: -30,
                }}>
                <Space>
                  <Button onClick={() => this.setState({ goodVisible: false })}>
                    取消
                  </Button>
                  <Button type="primary" htmlType="submit">
                    确认
                  </Button>
                </Space>
              </div>
            </Form.Item>
          </Form>
        </TheDialog>
        <TheDialog
          visible={logVisible}
          handleCancel={this.logDialogCancel}
          footer={null}
          title={'跟踪物流'}>
          <div style={{ height: 500, overflowY: 'auto' }}>
            {logisticsInformation && (
              <Steps
                progressDot
                current={logisticsInformation.length - 1}
                direction="vertical">
                {logisticsInformation.map((v) => {
                  return <Step title={v.time} description={v.desc} />
                })}
              </Steps>
            )}
            {!logisticsInformation && <span>暂无物流信息</span>}
          </div>
          <Space
            style={{
              display: 'flex',
              justifyContent: 'center',
              marginTop: 20,
            }}>
            <Button type={'primary'} onClick={this.logDialogCancel}>
              确定
            </Button>
          </Space>
        </TheDialog>
        <Negotiate ref={this.negotiateRef} shopOrderDetailId={this.props.dataSource.orderDetailVo.shopOrderDetailId}></Negotiate>
      </div>
    )
  }
}
